//
//  YFMyRecivedGiftsVC.m
//  project
//
//  Created by yefei on 2019/4/15.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFMyRecivedGiftsVC.h"
#import "YFMyGiftCell.h"
#import "YFMyRecivedGiftModel.h"
#import "YFGiftExchangeCashVC.h"

@interface YFMyRecivedGiftsVC ()
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *cashButton;

@property (nonatomic, strong) NSArray<YFMyRecivedGiftModel *> *giftArray;
@property (nonatomic, strong) NSArray <NSDictionary *> *selectedGiftArray;
@property (nonatomic, copy) NSString *giftJson;

/**
 是否全选
 */
@property (nonatomic, assign) BOOL isAllSelected;

@end

@implementation YFMyRecivedGiftsVC

- (void)dealloc {
    [mNotificationCenter removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigaitonBar.hidden = YES;
    [self setupViews];
    [self.collectionView.mj_header beginRefreshing];
    
    // 添加全选通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(allSelected:) name:NotificationSelectedAllGifts object:nil];
}

- (void)setupViews {
    [self setupCollectionView];
    self.giftArray = [NSArray array];
    self.cashButton.enabled = NO;
}

- (void)setupCollectionView {
    [self.collectionView registerNib:[UINib nibWithNibName:@"YFMyGiftCell" bundle:nil] forCellWithReuseIdentifier:@"YFMyGiftCell"];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 85, 0);
    @weakify(self)
    [self.collectionView refresh:^{
        @strongify(self)
        [self loadGifts];
    }];
    self.collectionView.emptyView = self.tipEmptyView;
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _giftArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YFMyGiftCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YFMyGiftCell" forIndexPath:indexPath];
    if (_giftArray && _giftArray.count > 0 && indexPath.row < _giftArray.count) {
        cell.model = _giftArray[indexPath.row];
    }
    cell.giftIsSelected = _isAllSelected;
    
    @weakify(self)
    cell.selectedAction = ^(BOOL isSelected, NSString * _Nonnull giftId, NSString * _Nonnull amount, NSString * _Nonnull price) {
        @strongify(self)
        [self setupSingleGiftStatus:isSelected giftId:giftId giftCount:amount price:price];
    };
    return  cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(13, 13, 13, 13);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((SCREEN_WIDTH - 30 - 26 - 24) / 4, (SCREEN_WIDTH - 30 - 26 - 24) / 4 * 1.2);
}


#pragma mark - 网络请求
- (void)loadGifts {
    NSString *postString = [Api stringByAppendingString:MyRecivedGiftApi];
    NSDictionary *params = @{
                             @"userId":[HJUserManager getUserModel].userId
                             };
    @weakify(self)
    [HJHttpTool post:postString params:params success:^(HJResponeds *result) {
        @strongify(self)
        LKLog(@"我收到的礼物：%@", result);
        if (result.isSuccess) {
            NSArray <YFMyRecivedGiftModel *> *modelArray = [NSArray yy_modelArrayWithClass:[YFMyRecivedGiftModel class] json:result.data];
            self.giftArray = modelArray;
            if (self.giftArray.count == 0) {
                self.tipEmptyView.message = @"暂无收到的礼物～";
            }
        } else {
            self.tipEmptyView.message = @"result.resultDesc";
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    } failure:^(id result) {
        self.tipEmptyView.message = @"网络出错啦～";
    }];
}

#pragma mark - 通知执行方法
- (void)allSelected:(NSNotification *)info {
    NSDictionary *userInfo = info.userInfo;
    BOOL isSelected = [userInfo[@"isSelected"] boolValue];
    self.isAllSelected = isSelected;
    [self.collectionView reloadData];
    [self setupAllGiftStatus:isSelected];
}

#pragma mark - 设置单个礼物的选中
- (void)setupSingleGiftStatus:(BOOL)isSelected giftId:(NSString *)giftId giftCount:(NSString *)amount price:(NSString *)price{
    NSMutableArray<NSDictionary *> *selectedArray = [NSMutableArray arrayWithArray:_selectedGiftArray];
    BOOL isRepeat = NO;
    NSDictionary *repeatDict = @{
                                 @"giftId": giftId,
                                 @"amount": amount,
                                 @"price": price
                                 };
    
    for (NSDictionary *model in selectedArray) {
        if ([model[@"giftId"] integerValue] == giftId.integerValue) {
            isRepeat = YES;
            repeatDict = model;
            break;
        }
    }
    
    if (isSelected) {
        if (!isRepeat) [selectedArray addObject:repeatDict];
    } else {
        if (isRepeat) [selectedArray removeObject:repeatDict];
    }
    
    self.selectedGiftArray = selectedArray;
    
    LKLog(@"单个选中：%@", self.selectedGiftArray);
    self.cashButton.enabled = self.selectedGiftArray.count != 0;
}

#pragma mark - 设置全选礼物选中
- (void)setupAllGiftStatus:(BOOL)isAllSelected {
    NSMutableArray<NSDictionary *> *selectedArray = [NSMutableArray arrayWithCapacity:self.giftArray.count];
    
    if (isAllSelected) {
        for (YFMyRecivedGiftModel *model in self.giftArray) {
            NSDictionary *selectedDict = @{
                                           @"giftId": model.giftId,
                                           @"amount": model.amount,
                                           @"price": model.price
                                           };
            [selectedArray addObject:selectedDict];
        }
        self.selectedGiftArray = selectedArray;
    } else {
        self.selectedGiftArray = selectedArray;
    }
    
    LKLog(@"全选中：%@", self.selectedGiftArray);
    self.cashButton.enabled = self.selectedGiftArray.count != 0;
}

#pragma mark - 数组转 json
- (NSString *)toJsonString:(NSArray *)selectedArray {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:selectedArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:(NSUTF8StringEncoding)];
    return jsonString;
}

#pragma mark - 兑换现金
- (IBAction)exchangeCash {
    NSInteger totalAmount = 0;
    CGFloat giftPrice = 0;
    CGFloat totalPrice = 0.f;
    CGFloat serviceCharge = 0;
    for (int i = 0; i < self.selectedGiftArray.count; i++) {
        NSDictionary *dict = self.selectedGiftArray[i];
        
        NSInteger amount = [dict[@"amount"] integerValue];
        CGFloat price = [dict[@"price"] floatValue];
        
        totalAmount += amount;
        giftPrice = price;
        totalPrice += price * amount;
        serviceCharge = 100.f;
    }
    
    YFGiftExchangeCashVC *vc = [YFGiftExchangeCashVC new];
    vc.price = [NSString stringWithFormat:@"%.2f", giftPrice];
    vc.totalAmount = [NSString stringWithFormat:@"%zd", totalAmount];
    vc.totalPrice = [NSString stringWithFormat:@"%.2f", totalPrice];
    vc.serviceCharge = [NSString stringWithFormat:@"%.2f", serviceCharge];
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
}

@end
